package com.whfc.common.util;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 压缩工具
 * @Author hw
 * @Date 2021-07-22 17:46
 * @Version 1.0
 */
public class ZipUtil {


    public static InputStream zipPdfFile(List<InputStream> iss) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(bos);
        zipOut.setEncoding("utf-8");
        iss.forEach(is -> {
            try {
                zipOut.putNextEntry(new ZipEntry(RandomUtil.getRandomFileName()+".pdf"));
                int count;
                while ((count = is.read()) != -1) {
                    zipOut.write(count);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        zipOut.closeEntry();
        zipOut.close();
        return new ByteArrayInputStream(bos.toByteArray());
    }

    public static void main(String[] args) throws IOException {
        List<InputStream> iss = new ArrayList<>();
        iss.add(new FileInputStream(new File("C:\\Users\\NING MEI\\Desktop\\1.pdf")));
        iss.add(new FileInputStream(new File("C:\\Users\\NING MEI\\Desktop\\新建文本文档.txt")));
        InputStream inputStream = zipPdfFile(iss);
        File file = new File("C:\\Users\\NING MEI\\Desktop\\" + RandomUtil.getRandomFileName() + ".zip");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        int count;
        while ((count = inputStream.read()) != -1) {
            fileOutputStream.write(count);
        }
        fileOutputStream.flush();
        fileOutputStream.close();

    }
}
